from django.shortcuts import render
from django.conf.urls import url, include
from rest_framework import routers, serializers, viewsets
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.models import User
from configs.models.NaturalPerson import NaturalPerson

# Serializers define the API representation.

from oauth2_provider.views.generic import ProtectedResourceView
from django.http import HttpResponse
from oauth2_provider.ext.rest_framework import TokenHasReadWriteScope
from rest_framework import permissions

# pagination 
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework import pagination
from django.db.models import Q
import operator
from operator import __or__ as OR
from functools import reduce



class ApiEndpoint(ProtectedResourceView):

    def get(self, request, *args, **kwargs):
        return HttpResponse('Hello, OAuth2!')


class NaturalPersonSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = NaturalPerson
        fields = ('id', 'last_name', 'first_name', 'birth_date')


class MiPermission(permissions.BasePermission):

    """
    Global permission check for blacklisted IPs.
    """

    def has_permission(self, request, view):
        if request.user.has_perms(('configs.add_escuela',)):
            return True
        return False
# ViewSets define the view behavior.




class GetPaginate(PageNumberPagination):
    page_size = 100
    page_size_query_param = 'page_size'
    max_page_size = 1000

    def get_paginated_response(self, data):
        return Response({
            'options': {
                'count': self.page.paginator.count,
                'pages': self.page.paginator.num_pages,
                'page': self.plus(),
                'start': self.page.start_index()-1,
                'end': self.page.end_index()-1,
                'next': self.siguente(),
                'previous': self.anterior(),
                'range': self.range()
            },
            'results': data
            })

    def siguente(self):
        if not self.page.has_next():
            return None
        page_number = self.page.next_page_number()
        return page_number

    def anterior(self):
        if not self.page.has_previous():
            return None
        page_number = self.page.previous_page_number()
        return page_number

    def plus(self):
        if not self.page.has_next():
            return None
        page = self.page.next_page_number()-1
        return page

    def range(self):
        total = self.page.paginator.count
        start = self.page.start_index()
        end = self.page.end_index()
        rangep = '{0} - {1} / {2}'.format(start, end, total)
        return rangep






class NaturalPersonViewSet(viewsets.ModelViewSet):
    lookup_field = 'id'
    queryset = NaturalPerson.objects.all()
    serializer_class = NaturalPersonSerializer
    pagination_class=GetPaginate

    #required_scopes = ['groups']
    #permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
    #permission_classes = [permissions.IsAuthenticated, MiPermission]

    def list(self, request, *args, **kwargs):
        query = request.query_params.get('query', None)
        field = request.query_params.get('field', 'id')
        order = request.query_params.get('order', '')

        if query is not None:

            queryall=(Q(id__icontains=query),
                Q(last_name__icontains=query),
                Q(first_name__icontains=query))

            data = self.get_queryset().filter(reduce(OR, queryall)).order_by(''+order+''+field+'')

            page = self.paginate_queryset(data)

            if page is not None:
                serializer = self.get_serializer(page, many=True)
                return self.get_paginated_response(serializer.data)
        else:
            data = self.get_queryset().order_by(''+order+''+field+'')
            page = self.paginate_queryset(data)
            if page is not None:
                serializer = self.get_serializer(page, many=True)
                return self.get_paginated_response(serializer.data)
